package com.theanh.RssActivity.util;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class ProgressBar extends ImageView {
	protected static final int UPDATE_IMAGE_MESSAGE = 0;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_IMAGE_MESSAGE:
				// Load image
				ProgressBar.this.setImageResource(images[count]);
				break;
			}
			super.handleMessage(msg);
		}
	};
	public ProgressBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public ProgressBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public ProgressBar(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	
	int count = 0;
	public int[] images;
	private static final int SLEEP_TIME = 400;
	private static final String TAG = "ProgressBar";
	private boolean running = false;
	
	
	public void start(){
		running = true;
		new Thread(){
			
			public void sendMessage(int identifier) {
				Message message = new Message();
				message.what = identifier;

				// send data to update GUI
				handler.sendMessage(message);
			}
			
			public void run(){
				if (images == null || images.length == 0)
					return;
				
				while(running){
					
					sendMessage(UPDATE_IMAGE_MESSAGE);
					
					if (count < images.length - 1)
						count++;
					else
						count = 0;
					
					// Check is running or not
					if (!running)
						 break;
					
					// Sleep this thread
					try {
						Thread.sleep(SLEEP_TIME);
					} catch (InterruptedException e) {
						Log.e(TAG,e.toString());
					}
				}
			}
		}.start();
	}
	
	public void stop(){
		running = false;
		//ProgressBar.this.setImageResource(images[images.length-1]);
	}
	
	public int[] getImages() {
		return images;
	}

	public void setImages(int[] images) {
		this.images = images;
	}
	
}
